package com.cx.base.day19_thread;


import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @Author: robert.song
 * @Date: Created in 2021/11/26
 * @Target: ABA问题本身不影响数据安全，下面是ABA案例
 */
@Slf4j
public class Thread_13_3_原子性_ABA {
    static AtomicReference<String> ref = new AtomicReference<>("A");

    public static void main(String[] args) throws InterruptedException {
        log.info("main start...");
//      获取值A
        String prev = ref.get();
//      中途有别的线程改动ref
        other();
//      虽然有线程改动数据，但是改动后的值仍然等于prev,这种情况依然可以改为C，称为ABA
        log.info("change A->C {}", ref.compareAndSet(prev, "C"));

    }

    private static void other() {
        Thread thread = new Thread(() -> {
//            改了又改回去了
            log.info("change A->B {}", ref.compareAndSet(ref.get(), "B"));
            log.info("change B->A {}", ref.compareAndSet(ref.get(), "A"));
        });
        thread.start();

    }
}
